/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Forms;

import Classes.MInterface;
import Classes.User;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.*;
import java.net.InetAddress;
import java.rmi.Naming;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JOptionPane;

/**
 *
 * @author hp
 */
public class _Login extends javax.swing.JFrame {
    static MInterface mi;
    static HashMap<String, String> credentials = null;
    static ArrayList<User> usersList = null;
    static String[] usernames;
    static User currentUser;
    static String userType;
    static String compIP = null;
    String serverAdd;
    static String ip;
    
    /**
     * Creates new form _Login
     */
    public _Login() {
        initComponents();
        this.setLocationRelativeTo(getRootPane());
        ipaddT.setEditable(true);
        
        try {
            compIP = InetAddress.getLocalHost().getHostAddress();
            FileInputStream fs = new FileInputStream("src" + File.separator + "Resources" + File.separator + "ip.txt");
            DataInputStream ds = new DataInputStream(fs);
            BufferedReader br = new BufferedReader(new InputStreamReader(ds));
            String s = br.readLine();
            if(s != null) {
                ipaddT.setText(s);
            }
            ds.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        usernameL = new javax.swing.JLabel();
        usernameT = new javax.swing.JTextField();
        passwordL = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        ipaddT = new javax.swing.JTextField();
        loginB = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        passwordT = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/banner.jpg"))); // NOI18N

        jSeparator2.setForeground(new java.awt.Color(0, 153, 51));

        usernameL.setFont(new java.awt.Font("Tahoma", 1, 14));
        usernameL.setText("Username:");

        usernameT.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                usernameTKeyTyped(evt);
            }
        });

        passwordL.setFont(new java.awt.Font("Tahoma", 1, 14));
        passwordL.setText("Password:");

        jSeparator3.setForeground(new java.awt.Color(0, 153, 51));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel4.setText("Server Address:");

        ipaddT.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ipaddTKeyTyped(evt);
            }
        });

        loginB.setFont(new java.awt.Font("Tahoma", 1, 14));
        loginB.setText("Login");
        loginB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginBActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton2.setText("Exit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(usernameL)
                        .addGap(18, 18, 18)
                        .addComponent(usernameT, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(passwordL)
                        .addGap(18, 18, 18)
                        .addComponent(passwordT, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))
                    .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(loginB, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ipaddT, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameL)
                    .addComponent(usernameT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(passwordL)
                    .addComponent(passwordT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(ipaddT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginB, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginBActionPerformed
        saveIt();        
    }//GEN-LAST:event_loginBActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            if(mi != null) {
                mi.clientActivity(compIP, "disconnect");
            }
            System.exit(0);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void usernameTKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameTKeyTyped
        String s = "!@#$%^&*()-+=~`|/?.>,<][}{;:\'\"";
        
        char c = evt.getKeyChar();
        if (s.contains(c + "") || c == KeyEvent.VK_BACK_SLASH || c == KeyEvent.VK_SPACE || c == KeyEvent.VK_ENTER) {
            if(c == KeyEvent.VK_ENTER) {
                saveIt();
            } else {
                evt.consume();
                JOptionPane.showMessageDialog (null, "Please enter allowed characters.", "Error", JOptionPane.ERROR_MESSAGE);
                usernameL.setForeground(Color.red);
            }
        }
    }//GEN-LAST:event_usernameTKeyTyped

    private void ipaddTKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ipaddTKeyTyped
        String s = "!@#$%^&*()-+=~`|/?>,<][}{;:\'\" abcdefghijklmnopqrstuvwxyz";
        char c = evt.getKeyChar();
    
        if (s.contains(c + "") || c == KeyEvent.VK_BACK_SLASH || c == KeyEvent.VK_SPACE || c == KeyEvent.VK_ENTER) {
            if(c == KeyEvent.VK_ENTER) {
                saveIt();
            } else {
                evt.consume();
                JOptionPane.showMessageDialog (null, "Please enter allowed characters.", "Error", JOptionPane.ERROR_MESSAGE);
                ipaddT.setForeground(Color.red);
            }
        }
    }//GEN-LAST:event_ipaddTKeyTyped

    public void saveIt() {
        String username = usernameT.getText();
        String password = String.valueOf(passwordT.getPassword());
        serverAdd = ipaddT.getText();

        try {      
            InetAddress inetAddress = InetAddress.getLocalHost();
            compIP = inetAddress.getHostAddress();

            mi = (MInterface) Naming.lookup("//" + serverAdd + "/meab");
            mi.clientActivity(compIP, "connect");
            FileWriter fw = new FileWriter("src" + File.separator + "resources" + File.separator + "ip.txt", false);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(ipaddT.getText());
            bw.close();
            
            usersList = (ArrayList<User>) mi.getList("getlist-users").clone();
            
            boolean in = mi.checkUserStatus(username);
            boolean valid = false;
            if(usernameT.getText().equals("") || passwordT.getText().equals("") || ipaddT.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Empty Textbox!", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                valid = mi.login(username, password, in);
                if(!valid) {
                    JOptionPane.showMessageDialog(null, "Invalid Login Credentials!", "Error", JOptionPane.ERROR_MESSAGE);
                } else if(valid) {
                    if(!in) {
                        Object o = mi.get("get-user", null, username);
                        currentUser = (User) o;
                        if(currentUser.getType().equals("Administrator")) {   
                            new _UAdmin(0, currentUser, mi).setVisible(true);
                        } else if(currentUser.getType().equals("Adviser")) {
                            _UAdmin ad = null;
                            new _UAdviser(currentUser, ad, mi).setVisible(true);
                        } else {
                            new _USecretary(0, currentUser, mi).setVisible(true);
                        }
                        JOptionPane.showMessageDialog(null, "Welcome " + currentUser.getGName() + "!", "Login Successful", JOptionPane.INFORMATION_MESSAGE);
                        this.setVisible(false);
                    }
                    
                    if(in) {
                        JOptionPane.showMessageDialog(null, username + " is already logged in!", "Login Error", JOptionPane.ERROR_MESSAGE);
                        passwordT.setText("");
                    }
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Cannot find server on given IP Address!", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void save(KeyEvent e) {
        if(e.getSource() == usernameT) {
            disableKeys(e, true);
        } else if(e.getSource() == ipaddT) {
            disableKeys(e, false);
        }
        
        if(e.getKeyChar() == KeyEvent.VK_ENTER) {
            saveIt();
        }
    }
    
    public void disableKeys(KeyEvent e, boolean username) {
        String s = "!@#$%^&*()-+=~`|/?.>,<][}{;:\'\"";
        
        char c = e.getKeyChar();
        if(!username) {
            if(c != '.' || !Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE) {
                e.consume();
            }
        } else {
            if (s.contains(c + "") || c == KeyEvent.VK_BACK_SLASH || c == KeyEvent.VK_SPACE) {
                e.consume();
            }
        }
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new _Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ipaddT;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JButton loginB;
    private javax.swing.JLabel passwordL;
    private javax.swing.JPasswordField passwordT;
    private javax.swing.JLabel usernameL;
    private javax.swing.JTextField usernameT;
    // End of variables declaration//GEN-END:variables
}
